<?php

/**
 * home actions.
 *
 * @package    Redsea20
 * @subpackage home
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class homeActions extends rbisActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
      //echo ResearchTable::getInstance()->getAllApprovalRequestsByStatus(Types::$RESEARCH_APPROVAL_STATUS[Types::$APPR_AWAITING], $this->getUser()->getAttribute('currentuser')->getId())->count();

      $userType = $request->getParameter('uType');

      /*
       * If user type (param value) is not set then show all community members
       * otherwise display requested group members
       */
      //$this->memberList = Entity::getRBISCommunity(Types::$COMMUNITY_MEMBER_TYPE[Types::$COMMUNITY_MEMBER_TYPE_ALL], $this->getUser()->getAttribute('currentuser')->getId());
    
      return sfView::SUCCESS;
  }

  public function executeMessageDetail(sfWebRequest $request)
  {
      if ($this->getRequestParameter('id') != null && $this->getRequestParameter('id') != "")
      {
          $currentUserId = $this->getUser()->getAttribute("currentuser")->getId();

          $this->message = Message::GetMessageContent($this->getRequestParameter('id'), $currentUserId);
          $this->messageSender = Entity::GetEntity($this->message->getFromentityid());

          // to display a kinda: conversation between between you and messagePeer name
          $this->messagePeer = ($this->messageSender->getId() == $currentUserId) ?
                  $this->message->getEntity() : $this->messageSender;
            //
            //    // Check the string if it already contains separator (i-e ###) then get it replaced with *** and at client side replace back to ###
            //    echo $message->getId()."###".Entity::GetEntity($message->getFromentityid())->getFirstname()."###".str_replace("###", "***", $message->getSubject())."###".str_replace("###","***",$message->getBody());
      }
      return sfView::SUCCESS;
  }
  
  /**
     *
     * @param sfWebRequest $request
     */
    public function executeMessages(sfWebRequest $request)
    {
        //RBISUtility::SendEmail('ali.dars@kaust.edu.sa', 'adars@saudioger.com', 'Testing Email (With Passed Mailer)-4', 'Testing RBIS Email Service');
        $this->form = new MessageForm();
        return sfView::SUCCESS;
    }

    public function executeConnectionAutocomplete(sfWebRequest $request)
    {
        $currentUser = $this->getUser()->getAttribute("currentuser");
        $term = $request->getParameter('term');
        
        $this->connectionDetail = $currentUser->GetConnectionListWithEmail($term);
        $friends = array();
        foreach($this->connectionDetail as $connDetail) {
            //              $friends = $friends.$connDetail->Entity["firstname"]." ".$connDetail->Entity["lastname"]." (".$connDetail["emailaddress"].")"."###";
            $entity['id'] = $connDetail['id'];
            $entity['value'] = $connDetail["emailaddress"];
            $entity['label'] = $connDetail->Entity["firstname"]." ".$connDetail->Entity["lastname"]." (".$connDetail["emailaddress"].")";
            array_push($friends, $entity);
        }
        //      echo $friends;
        //      return sfView::NONE;
        return $this->renderText(json_encode($friends));
    }

    public function executeSendMessage($request)
    {
        $params = $request->getParameter('message');

//        $toEntity = Entity::GetEntityByEmail(substr($params['email'], strrpos($params['email'], '(') + 1, -1) );
        $toEntity = Entity::GetEntityByEmail($params['email']);

        Message::createNewMessage($this->getUser()->getAttribute("currentuser")->getId(), $toEntity->getId(), $params['subject'], $params['body']);
        $this->getUser()->setFlash('msg', 'Message has been sent successfully!.');

        // Redirecting it to same page so that form will not be submitted again on F5
        $this->redirect("home/messages");

        //$temp = http_build_query($request->getParameter('message'));
        return sfView::NONE;
    }

    public function executeFriends(sfWebRequest $request)
    {
        if ($this->getRequestParameter('flag') != null && $this->getRequestParameter('flag') != "")
        {


        }
        return sfView::SUCCESS;
    }

    public function executeShowMessage(sfWebRequest $request)
    {

        //    $messageContent = "";
        if ($this->getRequestParameter('id') != null && $this->getRequestParameter('id') != "")
        {
            $this->message = Message::GetMessageContent($this->getRequestParameter('id'), $this->getUser()->getAttribute("currentuser")->getId());
            $this->messageSender = Entity::GetEntity($this->message->getFromentityid());
            //
            //    // Check the string if it already contains separator (i-e ###) then get it replaced with *** and at client side replace back to ###
            //    echo $message->getId()."###".Entity::GetEntity($message->getFromentityid())->getFirstname()."###".str_replace("###", "***", $message->getSubject())."###".str_replace("###","***",$message->getBody());
        }

        return sfView::SUCCESS;
    }

    public function executeDeleteMessage(sfWebRequest $request)
    {
        if ($this->getRequestParameter('id') != null && $this->getRequestParameter('id') != "")
        {
          $deleteStatus = Message::DeleteUserMessage($this->getRequestParameter('id'));

          echo $deleteStatus;
        }

        return sfView::NONE;
    }

    public function executeSendFriendRequest(sfWebRequest $request)
    {
        if ($this->getRequestParameter('txtRequestedIds') != null && $this->getRequestParameter('txtRequestedIds') != "")
        {
            $emailList = explode(",", $this->getRequestParameter('txtRequestedIds'));

            foreach ($emailList as $email) {
                RBISUtility::sendEmail($email, "[RBIS]Friend Request", "Dear Member, <BR/> You have requested by Fahmi, to be member of RBIS community. Please click the given below link to create an account at RBIS.<BR/> Thanks", $this->getUser()->getAttribute("currentuser")->getId());
            }

        }
        return sfView::NONE;
    }

    public function executeSendMessageReply(sfWebRequest $request)
    {
      //echo $this->getUser()->getAttribute("userid");
      MessageReply::createReply($this->getUser()->getAttribute("currentuser")->getId(), $request->getParameter('mid'), $request->getParameter('Reply'));

      // Redirecting it to same page so that form will not be submitted again on F5
      $this->redirect("home/messages");

      return sfView::NONE;

    }

    public function executeGetMessageReply(sfWebRequest $request)
    {
        if ($this->getRequestParameter('mid') != null && $this->getRequestParameter('mid') != "")
        {

            $currentMessage = Message::GetMessage($this->getRequestParameter('mid'));

            echo "<table>";

            foreach($currentMessage->getMessageReply() as $messageReply){
                $entity = Entity::GetEntity($messageReply->getFromEntityId());
                echo "<tr>";
                echo "<td rowspan=\"2\" width=\"50px\" valign=\"top\"/>";
                echo "<td><b>";
                echo $entity->getFirstname();
                echo "</b></td>";

                echo "<td>";
                echo $messageReply->getReplybody();
                echo "</td>";

                echo "</tr>";
            }
            echo "</table>";
        }


        return sfView::NONE;
    }

    public function getFriendList(bit $loadAll)
    {
      $result = Doctrine_Query::create()
                        ->select('COUNT(ec.id)')
                        ->from('entityconnection ec')
                        ->leftJoin('ec.Entity e')
                        ->where('e.id='.$this->getUser()->getAttribute('currentuser')->getId())
                        ->andwhere('ec.connectionstatustyperefid='.Types::$CONN_STATUS["PENDING"]);
    }

    public function executeVerifyUserCollaboration(sfWebRequest $request)
    {
        $researchId = $request->getParameter('rid');
        $userId = $request->getParameter('uid');

        if(isset ($researchId) && isset ($userId) && (Researchgroup::isUserCollaboratingForThisResearch($userId, $researchId) || Research::getResearch($researchId)->getEntityid() == $userId))
        {
            echo '1';
        }
        else
            echo '0';

        return sfView::NONE;
    }

    public function executeProfile(sfWebRequest $request) {
        $currentEntity = Entity::GetEntity( $this->getUser()->getAttribute('currentuser')->getId() );

        // Redirect to error if no user in session
        $this->forward404Unless($currentEntity, sprintf('Object user does not exist (%s).', $this->getUser()->getAttribute('currentuser')->getId()));

        $this->currentUser = new EntityForm($currentEntity);

        if($this->getRequest()->isMethod('post'))
        {
            $userAccount = $request->getParameter('entity');
            //$userPicture = $request->getFiles('flUserPicture');

            /*
             * As password field is required in EntityForm and we don't need
             * to display it on this form therefore assigning dummy value to
             * password fields just to by-pass the password validation.
             * Note: Password value will not change in db with this action
             */
            $userAccount['password'] = '123123123';
            $userAccount['password_check'] = '123123123';

            // Prints current form's name (i-e entity)
            //echo $this->currentUser->getName();

            //$this->currentUser->bind($userAccount);
            // http://www.nacho-martin.com/7
            // http://www.symfony-project.org/forms/1_4/en/02-Form-Validation#chapter_02_file_upload
            $this->currentUser->bind($userAccount, $request->getFiles('entity'));


            //echo $this->currentUser->getGlobalErrors();
            //echo $this->currentUser->getErrorSchema();

            if($this->currentUser->isValid())
            {
                 $picture = $this->currentUser->getValue('picture');

                 if(!empty ($picture))
                 {
                     // Upload image size should be less than defined one
                     if(filesize($picture->getTempName()) < sfConfig::get('app_MaxUploadImage_size'))
                     {
                        if(!empty ($picture))
                         {
                             try
                             {
                                 $fp = fopen($picture->getTempName(), 'r');
                                 $fileContent = fread($fp, filesize($picture->getTempName()));
                                 $this->getLogger()->debug('size of '.$picture->getTempName().':'.filesize($picture->getTempName()));
                                 fclose($fp);
                             }
                             catch(Exception $ex)
                             {
                                  die($ex->getMessage());
                             }
                         }

                        // Updating the Doctrine Object (Entity) through EntityFarm Values
                          $this->currentUser->updateObject();

                          // Saving an Entity
                          $updateEntity = $this->currentUser->save();

                          if(!empty ($picture))
                          {
                              /* Pictue is being loaded after FORM bind so changes will not
                               * apply until we re-save the object with picture
                               */
                              $updateEntity->setPicture( $fileContent);
                              $updateEntity->save();
                          }

                          $this->getUser()->setFlash('message', 'Information saved successfully.');
                     }
                     else
                     {
                         $this->getUser()->setFlash('message', 'Image size is too large (maximum allowed size is 1 MB)');
                     }

                 }
                 else
                 {
                     // Updating the Doctrine Object (Entity) through EntityFarm Values
                     $this->currentUser->updateObject();

                     // Saving an Entity
                     $updateEntity = $this->currentUser->save();
                      
                     $this->getUser()->setFlash('message', 'Information saved successfully.');

                 }
            }
        }
        else
        {
            $currentUserLogin = $currentEntity->Login[0];
            $this->currentUser->setDefault('emailaddress',$currentUserLogin->getEmailaddress());
            $this->currentUser->setDefault('password','123123123');
            $this->currentUser->setDefault('password_check','123123123');
        }

        return sfView::SUCCESS;
    }

    public function executeChangePassword(sfWebRequest $request) {
        $oldPassword = $request->getParameter('txtOldPassword');
        $newPassword = $request->getParameter('txtnewPassword');
       $confirmPassword = $request->getParameter('txtconfirmPassword');
        //$researchList = Doctrine_Core::getTable('ConfigurationToken')->findByTokenkey($tokenKey);

        if(isset ($oldPassword) && isset ($newPassword) && isset ($confirmPassword) &&
                $newPassword == $confirmPassword && 
                Login::verifyPassword($oldPassword, $this->getUser()->getAttribute('currentuser')->getId()))
        {
            Login::changePassword($oldPassword, $newPassword, $this->getUser()->getAttribute('currentuser')->getId());
            $this->getUser()->setFlash('message', 'Password has been changed');

            $this->redirect("home/profile");
        }
        else
        {
            $this->getUser()->setFlash('message', 'Sorry password cannot be changed. Please contact administrator');
        }

        return sfView::NONE;
    }

    public function executeUserProfile(sfWebRequest $request) {
        $encryptedEntityId = $request->getParameter('id');

        if(isset ($encryptedEntityId))
            $this->userid = RBISUtility::decryptURLParamValue ($encryptedEntityId);
        else
            $this->userid = $this->getUser()->getAttribute('currentuser')->getId();

        return sfView::SUCCESS;

    }
}
